<?php
/*
 * description：
 * author：wh
 * email：
 * createTime：{2024/6/23} {0:12} 
 */

namespace wanghua\general_utility_tools_php\framework\base;




use app\common\model\TabConf;
use think\Db;
use think\Request;
use wanghua\general_utility_tools_php\framework\BaseController;
use wanghua\general_utility_tools_php\tool\Tools;

/**
 * 微信专用权限架构
 *
 * Class BaseWechatAuthController
 * @package wanghua\general_utility_tools_php\framework\base
 */
class BaseWechatAuthController extends BaseController
{
    protected $wechat_user_table_name = 'fa_users';

    public function __construct()
    {
        parent::__construct();


        //首页提示语
        $this->assign('index_msg', cache('index_msg_alert_cache_time'));

        //线上环境加载微信授权
        if (config('sys_env') == 'PROD') {
            $wx_user_info = session('wx_user_info');
            if (empty($wx_user_info['openid'])) {
                //重定向之前，保存当前url, 在获取授权信息之后，回跳到授权之前的网页地址
                session('redirect_before_url_session', request()->url(true));
                $ver = Tools::get_thinkphp_version();
                if($ver == '5.0'){
                    $url = url('Wexinauth/usrAuth','',false,true);
                }else{
                    $url = request()->domain().url('Wexinauth/usrAuth');
                }
                //没有则重定向去授权
                return $this->redirect($url);
            }

            $this->saveWechatUser($wx_user_info);
        }




    }


    /**
     * desc：周期更新当前用户信息
     * author：wh
     * @param $wx_user_info
     */
    private function saveWechatUser($wx_user_info)
    {
        try {
            $wechat_user = $this->getWxUserByOpenid($wx_user_info['openid']);
            if (empty($wechat_user)) {
                return $this->insertInfo($wx_user_info);
            }
            //扩展，按周期更新,而不是不更新
            if (empty($wechat_user['update_time']) || time() - strtotime($wechat_user['update_time']) > 5 * 3600) {

                return $this->updateUser($wx_user_info);
            }


        } catch (\Exception $e) {
            Tools::log_to_write_txt([
                'error' => '存储异常.' . $e->getMessage(),
                'wx_user_info' => $wx_user_info,
                'error_info' => $e->getTraceAsString()
            ]);
        }
    }

    /**
     * desc：新增微信用户信息
     * author：wh
     * @param $wx_user_info \app\index\model\微信用户
     *
     * {
     * "openid":"or9D2vs863Ky5Py2ovkAiu9XFLO4",
     * "nickname":"起源果蔬副食大华",
     * "sex":0,
     * "language":"",
     * "city":"",
     * "province":"",
     * "country":"",
     * "headimgurl":"https://thirdwx.qlogo.cn/mmopen/vi_32/joiaA475nx3fJiaqx0ibdnWo4A7Q3uCgu2hsribI0ATLItORjuUgCSP8mCaBkqL61ibGojib4pQYX1djUhZpF5zoqpSg/132",
     * "privilege":[]
     * }
     */
    private function insertInfo(array $wx_user_info)
    {

        if (isset($wx_user_info['privilege'])) {
            $wx_user_info['privilege'] = json_encode($wx_user_info['privilege']);
        }
        $data = [
            'nickname' => $wx_user_info['nickname'],
            'country' => $wx_user_info['country'],
            'province' => $wx_user_info['province'],
            'city' => $wx_user_info['city'],
            'headimage' => $wx_user_info['headimgurl'],
            'language' => $wx_user_info['language'],
            'openid' => $wx_user_info['openid'],
            'unionid' => isset($wx_user_info['unionid']) ? $wx_user_info['unionid'] : '',
            'privilege' => $wx_user_info['privilege'],
            'sex' => $wx_user_info['sex'],
            'arm_group' => '',
            'score' => 0,//积分
            'group_buy_earnings' => 0,//拼团收益
            'water_drop_balance' => 0,//水滴
        ];
        self::tab($this->wechat_user_table_name)
            ->data($data)
            ->insert();
    }

    /**
     * desc：更新当前用户信息
     *
     * author：wh
     */
    private function updateUser($wx_user_info)
    {
        $data = [
            'nickname' => $wx_user_info['nickname'],
            'headimage' => $wx_user_info['headimgurl'],
            'unionid' => isset($wx_user_info['unionid']) ? $wx_user_info['unionid'] : '',
        ];
        self::tab($this->wechat_user_table_name)
            ->data($data)
            ->where('openid', index_user_openid())
            ->update();
    }

    /**
     * desc：根据unionid获取用户信息
     * author：wh
     * @param string $unionid
     */
    private function getWxUserByUnionid(string $unionid)
    {
        return Db::table($this->wechat_user_table_name)
            ->field('id')
            ->where('unionid', $unionid)
            ->find();
    }

    /**
     * desc：获取微信用户信息
     * author：wh
     * @param string $openid
     */
    private function getWxUserByOpenid(string $openid)
    {
        return Db::table($this->wechat_user_table_name)
            //->field('id')
            ->where('openid', $openid)
            ->find();
    }

    /**
     * desc：根据openid获取昵称
     * author：wh
     * @param string $openid
     */
    private function getNicknameByOpenid(string $openid)
    {
        return Db::table($this->wechat_user_table_name)
            ->where('openid', $openid)
            ->value('nickname');
    }




}